<?php
/**
 * 投注账变
 * @author Administrator
 *
 */
namespace app\admin\controller;

use app\admin\controller\Base;
use app\common\logic\LotteryCategory as LotteryCategoryLogic;
use app\common\model\BetTing as BetTingModel;
use think\Db;
use Workerman\Protocols\ProtocolInterface;
use app\common\model\HuiYuanSupervise;
class Betting extends Base
{
	protected $lottert_category=[];
	protected $betting_model=[];
	protected $ssc=[96,93,94,95,49,86,87,88,89,90,91,79,126,141,292,293,294,295];
	protected $cp = [1,4,8,16,25,28,61,62,63];
	//protected $connection = 'mysql://root1:root@192.168.1.120:3306/ssc_back#utf8';
	public function _initialize(){
		parent::_initialize();
		$this->lottert_category = new LotteryCategoryLogic();
		$this->betting_model = new BetTingModel();
		$c = input('param.czid');
		$this->assign('czid',$c);
		$this->member_model= new HuiYuanSupervise();
	}

	/**
	 * 投注记录：未结算、已结算、无效、额度
	 * @return Ambigous <\think\mixed, string>
	 */

	public function tz_list() {
	    //彩种分类
	    
	    $caizhong = $this->lottert_category->LotteryForSettlement();
	    $ticker = input('get.ticker')?input('get.ticker'):0;
	    $type = '';
	    $title = '';
	    if($ticker == 0 || empty($ticker)){
	        $tz_sql = 'touzhu_list_no';
	        $title = '未结算投注记录';
	    }else if($ticker == 1){
	        $tz_sql = 'touzhu_list_ok';
	        $title = '已结算投注记录';
	    }else if($ticker == 2){
	        $tz_sql = 'touzhu_list_sw';
	        $title = '无效投注记录';
	    }else if($ticker == 3){
			$tz_sql = 'touzhu_list_zh';
	        $title = '追号投注未结算记录';
	    }
		$res = $this->lottert_category->SettlementRecordList($tz_sql,$type);
		
		$query = $res['data'];
		$cur_je = 0;
		$pcje = 0;
		//当前页金额
		foreach($query as &$v) {
		    $cur_je += $v['tzje'];
		    $pcje += $v['zjje'];
		    //转换大小写
		    $v['name']=lcfirst($v['name']);
		}
		//条件区间金额
		$qjje = $res['qjje'];
		$zjje = $res['zjje'];
		$limit=input('limit');
		$this->assign('limit',$limit);
		$condition = array();
		$condition['us_sql'] = input('get.us_sql');
		$condition['qihao_sql'] = input('get.qihao_sql');
		$condition['sDate1'] = input('get.sDate1');
		$condition['sDate2'] = input('get.sDate2');
		$this->assign('ticker',$ticker);
		$this->assign('param',$condition);
		$this->assign('query',$query);
		$this->assign('ssc',$this->ssc);
		$this->assign('gcsc',$this->cp);

		$this->assign('cur_je',sprintf('%.2f',$cur_je));
		$this->assign('qjje',sprintf('%.2f',$qjje));
		$this->assign('pcje',sprintf('%.2f',$pcje));
		$this->assign('zjje',sprintf('%.2f',$zjje));
		$this->assign('title',$title);
		$this->assign('ticker',$ticker);
		$this->assign('caizhong',$caizhong);

		return $this->fetch();
	}
	public function tz_list_new() {
	    //彩种分类
	    
	    $caizhong = $this->lottert_category->LotteryForSettlement();
	    $ticker = input('get.ticker')?input('get.ticker'):0;
	    $type = '';
	    $title = '';
	    if($ticker == 0 || empty($ticker)){
	        $tz_sql = 'touzhu_list_no';
	        $title = '未结算投注记录';
	    }else if($ticker == 1){
	        $tz_sql = 'touzhu_list_ok';
	        $title = '已结算投注记录';
	    }else if($ticker == 2){
	        $tz_sql = 'touzhu_list_sw';
	        $title = '无效投注记录';
	    }
	    
		$res = $this->lottert_category->SettlementRecordList($tz_sql,$type);
		$query = $res['data'];
		$cur_je = 0;
		$pcje = 0;
		//当前页金额
		foreach($query as &$v) {
		    $cur_je += $v['tzje'];
		    $pcje += $v['zjje'];
		    $v['name']=lcfirst($v['name']);
		}
		//条件区间金额
		$qjje = $res['qjje'];
		$zjje = $res['zjje'];
		$limit=input('limit');
		$this->assign('limit',$limit);
		$condition = array();
		$condition['us_sql'] = input('get.us_sql');
		$condition['qihao_sql'] = input('get.qihao_sql');
		$condition['sDate1'] = input('get.sDate1');
		$condition['sDate2'] = input('get.sDate2');
		$this->assign('ticker',$ticker);
		$this->assign('param',$condition);
		$this->assign('query',$query);
		$this->assign('ssc',$this->ssc);
		$this->assign('gcsc',$this->cp);

		$this->assign('cur_je',sprintf('%.2f',$cur_je));
		$this->assign('qjje',sprintf('%.2f',$qjje));
		$this->assign('pcje',sprintf('%.2f',$pcje));
		$this->assign('zjje',sprintf('%.2f',$zjje));
		$this->assign('title',$title);
		$this->assign('ticker',$ticker);
		$this->assign('caizhong',$caizhong);

		return $this->fetch();
	}
	public function billList(){
		$caizhong = $this->lottert_category->LotteryForSettlement();
		$where = array();
		$us_sql = input('get.us_sql') ? input('get.us_sql') : '';
		$czid = input('czid') ? input('czid') : 0;
		if($czid!=0){
			$where['k.czid'] = input('get.czid');
		}
		$sDate1 = input('get.sDate1') ? strtotime(input('sDate1').' 00:00:00') : strtotime(date('Y-m-d 00:00:00'));
		$sDate2 = input('get.sDate2') ? strtotime(input('sDate2').' 23:59:59') : strtotime(date('Y-m-d 23:59:59'));
		if($us_sql!='') {
			$where['k.username'] = ['LIKE',"%{$us_sql}%"];
			$this->assign('us_sql',$us_sql);
		}
		
		$betweentime = [$sDate1,$sDate2];
		
		$this->assign('start',date('Y-m-d',$sDate1));
		$this->assign('end',date('Y-m-d',$sDate2));
		$user = Db::name('username')->where('nbzh',1)->column('username');
		$users = implode(',', $user);
		$touzhu = Db::name('touzhu_list_ok')
					->alias('k')
					->join('__CAIPAI_LIST__ c','c.id=k.czid')
					->field('k.id,k.username,k.czid,2 as type,k.tzje as je,k.tzhje,k.tz_time as cztime,k.fdje,c.cp_name_old,c.cp_name_new,zjje')
					->where('k.username','not in',$users)->where($where)->whereTime('k.tz_time','BETWEEN',$betweentime)
					->select();
		
		$touzhu_pc = Db::name('touzhu_list_pc')
						->alias('k')
						->join('__CAIPAI_LIST__ c','c.id=k.czid')
						->field('k.id,k.username,k.czid,1 as type,k.zjje as je,k.tzhje,k.rktime as cztime,k.fdje,c.cp_name_old,c.cp_name_new')
						->where('k.username','not in',$users)->where($where)->whereTime('k.tz_time','BETWEEN',$betweentime)
						->order('k.id desc,k.rktime desc')
						->select();
		
		$query = array_merge($touzhu,$touzhu_pc);
		foreach ($query as &$item){
		
			if(ctype_digit($item['cztime'])===false){
				$item['cztime'] = intval(strtotime($item['cztime']));
			}
			
		}
		if($query){
			array_multisort(array_column($query,'cztime'),SORT_DESC,array_column($query,'id'),SORT_DESC,$query);
		}
		$this->assign('query',$query);
		$this->assign('caizhong',$caizhong);
		$this->assign('time',$betweentime);
		
		return $this->fetch('bill_list');
	}
	
	 public function fs_list(){
	    $where = [];
	    $where['t.czid'] = array('neq',9);
        if(input('post.us_sql')){
            $where['t.username'] = input('post.us_sql');
            $this->assign('us_sql',$where['t.username']);
        }
        
        $condition['sDate1'] = input('post.sDate1') ? strtotime(input('post.sDate1')) : strtotime(date("Y-m-d",strtotime("-1 day")));
        $condition['sDate2'] = input('post.sDate2') ? strtotime(input('post.sDate2')) : strtotime(date("Y-m-d 23:59",strtotime("-1 day")));
	    
	    if(input('post.submit2')){
	        $name = input('post.user/a');
	        $this->fs_distribute($name,$condition['sDate1'],$condition['sDate2']);
	    }else{
    	    $condition['desc'] = input('get.desc');
    	    $time = [$condition['sDate1'],$condition['sDate2']];
    	    
    	    $list = Db::name('touzhu_list_ok')->alias('t')
    	    ->field('uc.fsbl,t.username,uc.class_name,SUM(t.tzje) as tzje,SUM(t.zjje) as zjje')
    	    ->join('__USERNAME__ u','u.username=t.username')
    	    ->join('__US_CLASS__ uc','uc.id=u.us_class')
    	    ->group('t.username,uc.fsbl,uc.class_name')
    	    ->whereTime('t.tz_time','BETWEEN',$time)
    	    ->where($where)
    	    ->where('t.fs',0)
    	    ->order('SUM(t.zjje)','DESC')
    	    ->select();
    	    $this->assign('list',$list);
	    }
	    
	    $this->assign('param',$condition);
	    
	    return $this->fetch();
	}
	
	private function fs_distribute($name=[],$start_time,$end_time){
	    if(!isset($name[0])){
	        $this->error('请选择用户!','/admin/Betting/fs_list');
	    }
	    $user = implode("','", $name );
	    
	    $list = Db::query("select t.username,sum(t.zjje) as zjje,sum(t.tzje) as tzje,u.us_class,c.class_name,c.fsbl from (kkty_touzhu_list_ok as t left join kkty_username as u on t.username=u.username) left join kkty_us_class as c on u.us_class=c.id WHERE t.username in ('{$user}') and t.czid <>9 and t.fs=0 and t.tz_time between '{$start_time}' and '{$end_time}' GROUP BY t.username,c.class_name,u.us_class,c.fsbl");
	    Db::startTrans();
	    try{
    	    foreach ($list as $v){
    	        $data = array();
    	        
    	        Db::name('touzhu_list_ok')->where('username',$v['username'])->whereTime('tz_time','between',[$start_time,$end_time])->update(['fs'=>1]);
    	        Db::name('username')->where('username',$v['username'])->setInc('je', round($v['tzje']/100*$v['fsbl'],2));
    	        $data['username'] = $v['username'];
    	        $data['us_class'] = $v['us_class'];
    	        $data['fsbl'] = $v['fsbl'];
    	        $data['tzje'] = $v['tzje'];
    	        $data['zjje'] = $v['zjje'];
    	        $data['fsje'] = round($v['tzje']/100*$v['fsbl']);
    	        $data['start_time'] = $start_time;
    	        $data['end_time'] = $end_time;
    	        $data['distribute_time'] = time();
    	        $data['czadmin'] = input('cookie.user');
    	        Db::name('fs_list')->insert($data);
    	        $this->member_model->caozuorizhi_xieru("给账户:".$data['username']."返水派送，派送金额:".$data['fsje']);
    	    }
    	    Db::commit();
	    }catch (\Exception $e){
	        Db::rollback();
	        alert_back('派送失败!');
	    }
	    
	    js_tishi('派送成功!', '/admin/Betting/fs_list');
	}
	
	
	public function fs_distribute_list(){
	    $where = array();
	    if(input('post.us_sql')){
	        $where['f.username'] = input('post.us_sql');
	    }
	    if(input('post.sDate1') && input('post.sDate2')){
	        $time = [input('sDate1'),input('sDate2')];
	    }else{
	        $time = [date('Y-m-d',time()-3600*24*30),date('Y-m-d',strtotime('+1 day'))];
	    }
	    $list = Db::name('fs_list')->alias('f')->join('us_class u','f.us_class=u.id')->where($where)->whereTime('distribute_time','between',$time)->field('f.username,f.fsbl,f.tzje,f.zjje,f.fsje,f.start_time,f.czadmin,f.end_time,f.distribute_time,u.class_name')->order('distribute_time desc')->select();
	    $this->assign('list',$list);
	    $this->assign('param',$where);
	    $this->assign('time',$time);
	    return $this->fetch();
	}
	//已开奖的投注记录
	public function tzxqlist() {
	
	
		$where['a.id']=$_GET['tzid'];
	
		$result=Db::name('touzhu_list_ok')
		->alias('a')
		->field(['a.fdje','a.id as uid','a.czid as czid','a.qihao as qihao','a.wfid as wfid','a.username as name','a.tzje as tzje','a.dzje as dzje','a.dqpl as dqpl','a.tzhm as tzhm','a.kjjg as kjhm','a.tz_time as tz_time','a.tzhje as tzhje','a.kjjg as kjjg','a.zjzs as zjzs','a.ifqs as ifqs','a.zjje as zjje','a.nbzh as nbzh'])
		->join('__USERNAME__ u','a.username=u.username')
		->field(['u.swzh'])
		->join('__PLAY_CLASSIFY__ b','b.id=a.wfid')
		->field(['b.class_name_mini as wanfa','b.digit as digit'])
		->join('__CAIPAI_LIST__ c','c.id=a.czid')
		->field(['c.cp_name_old as old_name','c.cp_name_new as new_name'])
		->where($where)
		->find();
	
	
		if(!empty($result['digit'])){
			$result['tzhm'] = digit($result['tzhm'],$result['digit'],$result['czid'],$result['wfid']);
		}
		$result['kjjg'] = kjjg_split($result['kjjg'],$result['czid'],true);
		if ($result['zjje']>0) {
			$result['zjzt']="已中奖";
		}else{
			$result['zjzt']="未中奖";
		}
		if($result['nbzh']==1){
			$result['nbzh']="元";
		}elseif ($result['nbzh']==2) {
			$result['nbzh']="角";
		}elseif ($result['nbzh']==3) {
			$result['nbzh']="分";
		}
		$this->assign('result',$result);
	
	
		/*var_dump($_GET['tzid']);*/
		return $this->fetch('tzxq_list');
	}
	public function zd_fenxi(){//注单分析

		$start=input('sDate1');
		$end=input('sDate2');
		$this->assign('start',$start);
		$this->assign('end',$end);
		$where1="";
	    if($start && $end){	    	
		    $where1['rktime']=['between',$start.','.$end];
	    }		
		$limit=input('limit');
		$this->assign('limit',$limit);
		$list=Db::name('caipai_list')->paginate(50,false,['query'=>request()->param()])->each(function($v,$k){
					$start=input('sDate1');
					$end=input('sDate2');
					$where1="";
				    if($start && $end){
				    	$start=input('sDate1')." 00:00:00";
				    	$end=input('sDate2')." 23:59:59";
					    $where1['rktime']=['between',$start.','.$end];
				    }
				    //未结算投注金额
					$count_no=Db::name('touzhu_list_no')->where('czid',$v['id'])->where($where1)->sum('tzje');
					//已结算投注金额（有效投注）
					$count_ok=Db::name('touzhu_list_ok')->where('czid',$v['id'])->where($where1)->sum('tzje');
					$v['count_ok']=$count_ok;
					$v['count_zong']=$count_no+$count_ok;//总投注金额
					$where=array('czid'=>$v['id'],'ifqs'=>1);
					$v['paicai_zong']=Db::name('touzhu_list_ok')->where($where)->where($where1)->sum('zjje');//总派彩金额
					$v['zhushu_zong']=Db::name('touzhu_list_ok')->where($where)->where($where1)->sum('tzzs');//总注数
					$v['zhushu_ying']=Db::name('touzhu_list_ok')->where($where)->where($where1)->where('zjje','>',0)->sum('tzzs');//赢（注数）
					$v['zhushu_shu']=Db::name('touzhu_list_ok')->where($where)->where($where1)->where('zjje',0)->sum('tzzs');//输（注数）
					$v['shenglv']="";//胜率
					$v['dengji']="无";//等级
					 if($v['zhushu_zong']!=0){
					    $v['shenglv']=intval($v['zhushu_ying'])/intval($v['zhushu_zong'])*100;
					    $v['shenglv']=round($v['shenglv'],2);
					    if($v['shenglv']>=50){
					    	$v['dengji']="高";
					    }elseif($v['shenglv']<=30){
					    	$v['dengji']="低";
					    }else{
					    	$v['dengji']="中";
					    }
					}
					$v['yingkui']=$v['paicai_zong']-$v['count_ok'];//盈亏
					return $v;
				});
		$this->assign('list',$list);
		return $this->fetch('zd_fenxi');
	}
}